package com.zzyl.common.utils.ai;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Component
public class AIModelInvoker {
    //首先明确这个工具类的作用是什么：这里是帮助我们使用api调用方式，将提示词发送给百度大模型
    //提示词具体怎么拼接是service考虑的事情，这里只用最终的prompt发送，再把需要的结果返回
    //并获取返回的JSON结果，解析完成后，将其转成JSON对象，返回给调用者，在service层再进行数据拿取
    //将参数封装进对象中，修改数据库。
    public String invoke(String prompt) throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer bce-v3/ALTAK-uTvVUJ9x2fwCT3oBcb6qO/e372404d235fc665665611817e928b389cd65bec");

        // 构建请求对象
        List<Message> messages = new ArrayList<>();
        messages.add(new Message("system", "平台助手"));
        messages.add(new Message("user", prompt));

        ChatRequest request = new ChatRequest("ernie-4.0-turbo-8k", messages);

        // 使用Jackson将对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = objectMapper.writeValueAsString(request);

        // 然后继续构建HttpEntity并发送请求...
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<String> response = restTemplate.exchange(
                "https://qianfan.baidubce.com/v2/chat/completions",
                HttpMethod.POST,
                entity,
                String.class
        );

        // 解析响应JSON并提取content
        String jsonResponse = response.getBody();
        String content = extractContentFromJson(jsonResponse);

        System.out.println(content);

        return content;
    }

    /**
     * 从JSON响应中提取content字段
     * @param jsonResponse JSON格式的响应字符串
     * @return content字段的内容
     * @throws JsonProcessingException JSON解析异常
     */
    private String extractContentFromJson(String jsonResponse) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonResponse);

        // 导航到content字段的路径: choices[0].message.content
        return rootNode.path("choices")
                .get(0)
                .path("message")
                .path("content")
                .asText();
    }

}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Message {
    private String role;
    private String content;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class ChatRequest {
    private String model;
    private List<Message> messages;
}
